// pages/tryCoursePlay/tryCoursePlay.js

import { secToTime } from '../../utils/util.js'
var app = getApp();

Page({

  /**
   * 页面的初始数据 
   */
  data: {
    progress: 0,
    duration: 0,  // 总时长
    formatDuration: '00:00',  // 格式化总时长
    currentTime: 0,  // 当前播放进度
    newcurrentTime: 0, // 拖动的进度
    isMovingSlider:false,
    currentFormatDuration: '00:00',  // 播放进度格式化
    speed: 0,
    step:1,
    endedMark:0,
    playOrStop: { play: '../../images/play3.png', stop: '../../images/play.png', status:true},
    // musicUrl: 'http://122.228.254.5/mp3.9ku.com/mp3/371/370924.mp3',
    musicUrl: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log('-----onLoad----');
    var paused = app.globalBackgroundAudioManager.paused;

    if (paused===undefined){
      that.audioInit();
    }else{
      console.log(app.globalBackgroundAudioManager);
    }
    
  },
  
  // 播放/暂停 音乐
  fnPlayOrStopMusic(){
    var that = this;
    var property = 'playOrStop.status';
    if (that.data.endedMark){  // 已经播放完毕
      that.audioInit();
    }
    that.setData({
      [property]: !that.data.playOrStop.status
    })

    if (that.data.playOrStop.status){
      app.globalBackgroundAudioManager.play()
    }else{
      app.globalBackgroundAudioManager.pause()
    }

  },

   /**
      * 总进度 100%；每一秒走1%
      * 总时长 5分 => 300s 1=x/3,每秒走0.33%
      * 获取当前播放长度 curTime，left = curTime * 0.33
      * 当curTime 总时长，播放完毕，left = 100;
      *
    */
  audioInit() {
    var that = this;
    var speed = 0;
    app.globalBackgroundAudioManager.title = '此时此刻'
    app.globalBackgroundAudioManager.epname = '此时此刻'
    app.globalBackgroundAudioManager.singer = '许巍'
    app.globalBackgroundAudioManager.coverImgUrl = 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000'
    // app.globalBackgroundAudioManager.src = that.data.musicUrl // 设置了 src 之后会自动播放
    // todo 
    
    app.globalBackgroundAudioManager.src = app.handleAudioSrc(2); // 设置了 src 之后会自动播放

    setTimeout(function () {
      // wx.pauseBackgroundAudio();  // 初始化暂停
      var time = Math.round(app.globalBackgroundAudioManager.duration);
      that.setData({
        duration: time,
        formatDuration: secToTime(time),
        speed: (100 / time).toFixed(3)
      })
    },500)
  },

  // 等待加载
  onWaiting(){
    var that = this;
    app.globalBackgroundAudioManager.onWaiting(()=>{
        wx.showLoading({
          title: '加载音频中...',
        })
    })
  },

  // 可以播放状态
  onCanplay(){
    app.globalBackgroundAudioManager.onCanplay(() => {
      setTimeout(()=>{
        wx.hideLoading();
      },500)
    })
  },


  // 进度条
  onTimeUpdate(){
    var that = this;
    var speed = 0;
    app.globalBackgroundAudioManager.onTimeUpdate(function () {

      if (!that.data.duration ||that.data. formatDuration=='00:00') {
        that.setData({ duration: Math.round(app.globalBackgroundAudioManager.duration), formatDuration: secToTime(that.data.duration) })
      }

      if (!that.data.speed && that.data.speed <= 0) {
        speed = (100 / that.data.duration).toFixed(3);
      }

      var active = Math.floor(app.globalBackgroundAudioManager.currentTime)
      console.log('globalBackgroundAudioManager.currentTime->active', active);


      if (!that.data.isMovingSlider) {
        that.setData({
          speed: speed,
          progress: speed * active,
          currentFormatDuration: secToTime(active),
        })
      }

      app.globalData.globalCurrentTime = active;
      app.globalData.globalProgress = speed * active;
      console.log('speed', speed, 'active', active, 'progress', that.data.progress);
    })
  },

  onEnded(){
    var that = this;
    app.globalBackgroundAudioManager.onEnded(function(){
      var property = 'playOrStop.status';
      that.setData({
        [property]: !that.data.playOrStop.status,
        progress: 100,
        endedMark: 1,
      })

      console.log('---onEnded---');
    })
  },

  //  拖动进度条
  handleSliderChange(e) {
    let that = this;
    let val = e.detail.value;
    // console.log(e);
    // 修改播放时间  progress = speed * currentTime
    let newcurrentTime = Math.floor(val / that.data.speed);

    console.log('paused',app.globalBackgroundAudioManager.paused);
    console.log('修改播放时间', newcurrentTime);
    // 设置播放进度
    // app.globalBackgroundAudioManager.seek({ position: newcurrentTime});
    wx.seekBackgroundAudio({ position: newcurrentTime })
    // app.globalBackgroundAudioManager.currentTime = newcurrentTime;
    
    console.log('seek', app.globalBackgroundAudioManager.seek);


    //设置当前进度
    if (that.data.isMovingSlider){
      that.setData({ progress: val, currentFormatDuration: secToTime(newcurrentTime), newcurrentTime })
      app.globalData.globalCurrentTime = newcurrentTime;
    }
   
    
    
  },

  handleSliderMoveStart() {
    this.setData({
      isMovingSlider: true
    });
  },
  handleSliderMoveEnd() {
    this.setData({
      isMovingSlider: false
    });
  },



  /**
   * 课后作业
   */
  fnMyWork(){
    wx.navigateTo({
      url: '../myWork/myWork',
    })
  },

  /**
   * 立即报名
   */
  fnPayment(){
    wx.navigateTo({
      url: '../payment/payment',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log('----onReady----');
  },

  /**
   * 生命周期函数--监听页面显示  
   */
  onShow: function () {
    console.log('-----onShow---');
    var that = this
    that.onTimeUpdate();
    that.onEnded();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})